﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace MvcClient.Pages
{
    public class CallApiModel : PageModel
    {
        //public void OnGet()
        //{

        //}
        public string Message { get; set; }

        public string ApiUserClaimsJson { get; set; }

        public string ClientUserClaimsJson { get; set; }

        public string AccessToken { get; set; }

        public string RefreshToken { get; set; }

        private readonly IHttpClientFactory _httpClientFactory;

        public CallApiModel(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }

        //public void OnGet()
        public async Task<IActionResult> OnGetAsync()
        {
            var accessToken = await HttpContext.GetTokenAsync("access_token");

            var client = _httpClientFactory.CreateClient();
            //client.BaseAddress = new Uri("http://api.github.com");
            //string result = await client.GetStringAsync("/");

            //var client = new HttpClient();
            //client.SetBearerToken(accessToken);
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            //var content = await client.GetStringAsync("https://localhost:5001/api/values");
            var response = await client.GetAsync("https://localhost:5001/api/values");
            if (!response.IsSuccessStatusCode)
            {
                ApiUserClaimsJson = $"没有权限访问 https://localhost:5001/api/values , 状态码：{response.StatusCode.ToString()}";
            }
            else
            {
                var content = response.Content.ReadAsStringAsync().Result;
                ApiUserClaimsJson = JArray.Parse(content).ToString();
            }

            Message = "Your application description page.";
            ClientUserClaimsJson = JsonConvert.SerializeObject(from c in User.Claims select new { c.Type, c.Value });

            RefreshToken = await HttpContext.GetTokenAsync("refresh_token");
            AccessToken = accessToken;

            return Page();
        }
    }
}